import os
import re
import subprocess
from colorama import Fore, Style

from Shell.core.conversation import get_response
from Shell.utils.config_manager import get_model_config


def execute_command(command):
    # 使用正则表达式去除 '```powershell' 和 '```'
    command = re.sub(r'```powershell', '', command).strip()
    command = re.sub(r'```', '', command).strip()

    # 从配置文件中获取模型名称
    model_config = get_model_config("Model")
    model_name = model_config.get("model_name", "pixtral-large-latest")

    if command.startswith("cd"):
        # 处理 cd 命令
        try:
            print(Fore.WHITE + command + Style.RESET_ALL)
            target_dir = command.split()[1]
            os.chdir(target_dir)
            print(Fore.YELLOW + f"Current directory: {os.getcwd()}" + Style.RESET_ALL)
        except Exception as e:
            print(Fore.RED + f"Error: {e}" + Style.RESET_ALL)
            assistant_response = get_response(f"Error: {e}", model_name)
            execute_command(assistant_response)
    elif command.startswith("Set-Location -Path"):
        # 处理 Set-Location 命令
        try:
            print(Fore.WHITE + command + Style.RESET_ALL)
            target_dir = command.split()[2]
            os.chdir(target_dir)
            print(Fore.YELLOW + f"Current directory: {os.getcwd()}" + Style.RESET_ALL)
        except Exception as e:
            print(Fore.RED + f"Error: {e}" + Style.RESET_ALL)
            # 获取本地路径
            get_pwd = os.getcwd()  # 获取当前路径
            assistant_response = get_response(f"Error: {e} ,本地路径为:{get_pwd} , 报错了请使用cd命令。", model_name)
            execute_command(assistant_response)
    else:
        # 使用 subprocess 调用 PowerShell 命令
        result = subprocess.run(["powershell", "-Command", command], capture_output=True, text=True)
        if result.returncode != 0:
            error_message = f"Error: {result.stderr}，注意以powershell命令写出内容。"
            print(Fore.RED + error_message + Style.RESET_ALL)
            # 将错误信息发送给 AI
            assistant_response = get_response(error_message, model_name)
            # 如果 AI 建议执行命令，则执行命令
            execute_command(assistant_response)

        elif command.startswith("Write-Output"):
            output = result.stdout.strip()
            print(Fore.BLUE + output + Style.RESET_ALL)

        elif command.startswith("echo"):
            # result = subprocess.run(["powershell", "-Command", command], capture_output=True, text=True)
            print(Fore.BLUE + result.stdout.strip() + Style.RESET_ALL)

        # 包含Get的时候
        elif "Get" in command:
            output = result.stdout.strip()
            print(Fore.WHITE + command + Style.RESET_ALL)
            print(Fore.YELLOW + output + Style.RESET_ALL)
            # 如果命令是读取文件内容，将内容发送给 AI
            # 发送给ai
            assistant_response = get_response(output, model_name)
            execute_command(assistant_response)

        else:
            output = result.stdout.strip()
            print(Fore.WHITE + command + Style.RESET_ALL)
            print(Fore.YELLOW + output + Style.RESET_ALL)
            # 如果命令是读取文件内容，将内容发送给 AI
            if "Get-Content" in command:
                try:
                    assistant_response = get_response(output, model_name)
                    execute_command(assistant_response)
                except Exception as e:
                    print(Fore.RED + f"Error: {e}" + Style.RESET_ALL)
                    execute_command(str(e))
